#! /usr/bin/python
# -*- coding: cp1250 -*-

import os
import re
import sys
import string
import pepe.p_dm.sdb as s
unds = lambda x: re.sub('\W', '_', x) # replace all \W with undescore

def main(db):
    """ Lists keys in shelve database.
    """
    keys = s.slist(db)
    kcnt = len(s.slist(db))
    dbnm = os.path.split(db)[1]
    varData = "%s_data" % (unds(dbnm)[:-4])
    read = string.join(["""%s_%s = s.sread('%s', '%s')"""
                       % (unds(dbnm)[:-4], unds(x), x, db) for x in keys], "\n")
    hddt = ''
    if 'meta' in keys:
        meta = s.sread('meta', db)
        hdr = meta['header']
        if hdr <> '':
            hddt = string.join(["""\n    r[%d]  # %s""" % (i, v) for i,v in enumerate(hdr)], "")
            #hddt = string.join([str((i, v)) for i,v in enumerate(hdr)], "\n    ")
    print """import pepe.p_dm.sdb as s\n\n# shelve database : %s\n%s\n""" % (dbnm, read)
    if hddt <> '' : print """# header & data:\n\nfor r in %s:\n    '''%s\n    '''\n""" % (varData, hddt)

if __name__ == "__main__":
    """ """
    if len(sys.argv) == 2:
	main(sys.argv[1])
    else:
	main.__doc__
